package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.AuditOpinionsResult;
import com.itheima.common.ResponseResult;
import com.itheima.common.SetRecordsResult;
import com.itheima.mapper.*;
import com.itheima.pojo.*;
import com.itheima.service.QuestionsService;
import com.itheima.service.UsersService;
import com.itheima.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *
 */
@Service
public class QuestionsServiceImpl extends ServiceImpl<HmQuestionsAuditsMapper, HmQuestionsAudits> implements QuestionsService {

    @Autowired
    private HmQuestionsAuditsMapper hmQuestionsAuditsMapper;
    @Autowired
    private HmQuestionsRecordsMapper hmQuestionsRecordsMapper;
    @Autowired
    private HmQuestionsOptionsMapper hmQuestionsOptionsMapper;
    @Autowired
    private HmQuestionsMapper hmQuestionsMapper;
    @Autowired
    private HmCompanysMapper hmCompanysMapper;
    @Autowired
    private SubjectMapper subjectMapper;
    @Autowired
    private HmSubjectsDirectorysMapper hmSubjectsDirectorysMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private UsersService usersService;


    private HmQuestions hmQuestions = new HmQuestions();

    /**
     * 审核意见
     *
     * @param id
     * @return
     */
    @Override
    public AuditOpinionsResult auditOpinions(Integer id) {
        HmQuestionsAudits hmQuestionsAudits = hmQuestionsAuditsMapper.selectById(id);
        AuditOpinionsResult auditOpinionsResult = new AuditOpinionsResult();
        auditOpinionsResult.setOpinion(hmQuestionsAudits.getRemarks());//意见
        auditOpinionsResult.setChkTime(hmQuestionsAudits.getChktime().toString());//时间
        auditOpinionsResult.setChecker(hmQuestionsAudits.getCheckerid() + "");//审核人
        return auditOpinionsResult;
    }

    /**
     * 出题记录
     *
     * @param id
     * @return
     */
    @Override
    public SetRecordsResult setRecords(Integer id) {
        HmQuestionsRecords hmQuestionsRecords = hmQuestionsRecordsMapper.selectById(id);
        //对象转换
        String jsonString = JSON.toJSONString(hmQuestionsRecords);
        //获得返回值对象
        SetRecordsResult setRecordsResult = JSON.parseObject(jsonString, SetRecordsResult.class);
        //数据封装
        setRecordsResult.setSetter(hmQuestionsRecords.getSetterID() + "");
        return setRecordsResult;
    }



    /**
     * 基础题库列表
     *
     * @param query
     * @return
     */
    @Override
    public PageResult findPage(Query query) {
        Integer page = query.getPage();//当前页码
        Integer pagesize = query.getPagesize();//每页条数
        String shortName = query.getShortName();//获取到参数企业简称
        //企业管理条件判断
        LambdaQueryWrapper<HmCompanys> hmCompanyswrapper = new LambdaQueryWrapper<>();
        hmCompanyswrapper.like(HmCompanys::getShortName, shortName);
        List<HmCompanys> hmCompanys = hmCompanysMapper.selectList(hmCompanyswrapper);//根据企业简称查询到数据
        Integer[] ids=null;
        if (hmCompanys!=null){
            //将企业对象的所有id存入到数组当中
            ids = new Integer[hmCompanys.size()];
            for (int i = 0; i < hmCompanys.size(); i++) {
                ids[i] = hmCompanys.get(i).getId();
            }
        }
        //分页查询
        IPage<HmQuestions> p = new Page<>(page, pagesize);
        //todo 基础题库条件判断
        LambdaQueryWrapper<HmQuestions> wrapper = new LambdaQueryWrapper<>();
        //调用判断方法
        ifpanduan(query, ids, wrapper);
        IPage<HmQuestions> hmQuestionsIPage = hmQuestionsMapper.selectPage(p, wrapper);
        List<HmQuestions> hmQuestionsList = hmQuestionsIPage.getRecords();
        //遍历封装
        for (HmQuestions questions : hmQuestionsList) {
            //获得学科的id
            Integer subjectID = questions.getSubjectID();
            //查询学科并且封装
            HmSubjects hmSubjects = subjectMapper.selectById(subjectID);
            if (null!=hmSubjects){
                questions.setSubject(hmSubjects.getSubjectname());
            }
            //查询目录名称并且封装
            HmSubjectsDirectorys hmSubjectsDirectorys = hmSubjectsDirectorysMapper.selectById(questions.getCatalogID());
            if (null!=hmSubjectsDirectorys){
                questions.setCatalog(hmSubjectsDirectorys.getDirectoryName());
            }
            BsUser bsUser = usersMapper.selectById(questions.getCreatorID());
            if (null!=bsUser){
                //根据创建人id查找到创建人i姓名,并进行封装
                questions.setCreator(bsUser.getUsername());
            }

            //根据题库id查询到审核id
            LambdaQueryWrapper<HmQuestionsAudits> wrapperAudits=new LambdaQueryWrapper<>();
            wrapperAudits.eq(HmQuestionsAudits::getQuestionsID,questions.getId());
            HmQuestionsAudits hmQuestionsAudits = hmQuestionsAuditsMapper.selectOne(wrapperAudits);
            if (null!=hmQuestionsAudits){
                //审核人id
                Integer checkerid = hmQuestionsAudits.getCheckerid();
                //根据审核id查询审核姓名
                BsUser bsUser1 = usersMapper.selectById(checkerid);
                if (null!=bsUser1){
                    //根据创建人id查找到创建人i姓名,并进行封装
                    questions.setChkUser(bsUser.getUsername());
                }
            }
        }
        //创建返回值对象
        PageResult pageResult = new PageResult();
        //封装返回值数据
        pageResult.setCounts((int) hmQuestionsIPage.getTotal());
        pageResult.setPagesize(hmQuestionsIPage.getSize() + "");
        pageResult.setPages((int) hmQuestionsIPage.getPages());
        pageResult.setPage(page + "");
        pageResult.setItems(hmQuestionsList);
        return pageResult;
    }

    /**
     * 基础题库删除
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteById(Integer id) {
        hmQuestionsMapper.deleteById(id);
        return new ResponseResult(true);
    }

    /**
     * 基础题库新增
     * @param hmQuestions
     * @return
     */
    @Override
    public QuestionsAddResult add(HmQuestions hmQuestions) {
        //补全数据
        hmQuestions.setAddDate(new Date());// 创建日期
        hmQuestions.setNumber(UUID.randomUUID().toString());
        hmQuestions.setChkState(0);//筛选状态
        hmQuestions.setPublishdate(new Date());//发布时间
        hmQuestions.setPublishState(0);//发布状态
        hmQuestionsMapper.insert(hmQuestions);
        //获取到问题选项
        List<HmQuestionsOptions> options = hmQuestions.getOptions();
        if (options.size()!=0){
            for (HmQuestionsOptions hmQuestionsOptions : options) {
                //封装数据
                hmQuestionsOptions.setQuestionsID(hmQuestions.getId());
                //添加问题列表答案
                hmQuestionsOptionsMapper.insert(hmQuestionsOptions);
            }
        }
        QuestionsAddResult questionsAddResult = new QuestionsAddResult();
        questionsAddResult.setId(hmQuestions.getId());
        return questionsAddResult;
    }

    /**
     * 基础题库详情
     */
    @Override
    public QuestionAdd findById(Integer id) {
        //根据题库的id查询数据
        HmQuestions hmQuestions = hmQuestionsMapper.selectById(id);
        //根据题库id查询问题对象
        LambdaQueryWrapper<HmQuestionsOptions> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(HmQuestionsOptions::getQuestionsID,id);
        List<HmQuestionsOptions> hmQuestionsOptions = hmQuestionsOptionsMapper.selectList(wrapper);
        //封装数据
        hmQuestions.setOptions(hmQuestionsOptions);
        //通过学科id查找到学科名称
        String subjectname = subjectMapper.selectById(hmQuestions.getSubjectID()).getSubjectname();
        //通过目录id查找到目录名称集合
        LambdaQueryWrapper<HmSubjectsDirectorys> wrapperDirectory=new LambdaQueryWrapper<>();
        wrapperDirectory.eq(HmSubjectsDirectorys::getSubjectID,hmQuestions.getSubjectID());
        List<HmSubjectsDirectorys> hmSubjectsDirectorys = hmSubjectsDirectorysMapper.selectList(wrapperDirectory);
        //创建数组封装数据
        String[]directoryName=new String[hmSubjectsDirectorys.size()];
        for (int i = 0; i < hmSubjectsDirectorys.size(); i++) {
            directoryName[i]=hmSubjectsDirectorys.get(i).getDirectoryName();
        }
        hmQuestions.setSubjectName(subjectname);//封装学科名称
        hmQuestions.setDirectoryName(directoryName);//封装目录名称

        //类型转换
        String jsonString = JSON.toJSONString(hmQuestions);
        QuestionAdd questionAdd = JSON.parseObject(jsonString, QuestionAdd.class);
        return questionAdd;
    }

    /**
     * 基础题库修改
     */
    @Override
    public ResponseResult modify(HmQuestions hmQuestions) {
        //首先修改基础题库的数据
        hmQuestionsMapper.updateById(hmQuestions);
        //修改问题列表数据
        List<HmQuestionsOptions> hmQuestionsOptions = hmQuestions.getOptions();
        //遍历修改
        for (HmQuestionsOptions hmQuestionsOption : hmQuestionsOptions) {
            hmQuestionsOptionsMapper.updateById(hmQuestionsOption);
        }
        return new ResponseResult(true);
    }

    /**
     * 精选题库上下架
     * @param id
     * @param publishState
     * @return
     */
    @Override
    public ResponseResult modifyByPublishState(Integer id, Integer publishState) {
        //进行条件判断并修改
        LambdaUpdateWrapper<HmQuestions> wrapper=new LambdaUpdateWrapper<>();
        wrapper.eq(HmQuestions::getId,id).set(HmQuestions::getPublishState,publishState);
        hmQuestionsMapper.update(hmQuestions,wrapper);
        //创建试题出题对象
        HmQuestionsRecords hmQuestionsRecords = new HmQuestionsRecords();
        //封装数据
        if (publishState==0){
            //下架
            hmQuestionsRecords.setOperation("下架");
        }else {
            //上架
            hmQuestionsRecords.setOperation("上架");
        }
        hmQuestionsRecords.setQuestionsID(id);//题库id
        hmQuestionsRecords.setSetTime(new Date());//修改时间
        //根据题库id查找到出题人id
        Integer creatorID = hmQuestionsMapper.selectById(id).getCreatorID();
        hmQuestionsRecords.setSetterID(creatorID); //出题人id
        //添加试题出题记录
        hmQuestionsRecordsMapper.insert(hmQuestionsRecords);
        return new ResponseResult(true);
    }


    /**
     * 加入或移出精选
     * @param id
     * @param choiceState
     * @return
     */
    @Override
    public ResponseResult modifyByChoiceState(Integer id, Integer choiceState) {
        //条件判断,修改精选状态
        LambdaUpdateWrapper<HmQuestions> wrapper=new LambdaUpdateWrapper<>();
        wrapper.eq(HmQuestions::getId,id).set(HmQuestions::getIschoice,choiceState);
        hmQuestionsMapper.update(hmQuestions,wrapper);
        return new ResponseResult(true);
    }

    /**
     * 试题审核
     * @param id
     * @param hmQuestions
     * @return
     */
    @Override
    public ResponseResult modifyByChkstate(Integer id, HmQuestions hmQuestions,String s) {
        //封装数据
        hmQuestions.setId(id);
        hmQuestionsMapper.updateById(hmQuestions);
        //创建审核意见对象
        HmQuestionsAudits hmQuestionsAudits = new HmQuestionsAudits();
        //封装审核意见数据
        hmQuestionsAudits.setQuestionsID(id);//题库id
        hmQuestionsAudits.setRemarks(hmQuestions.getChkRemarks());//试题意见
        if (hmQuestions.getChkState()==1){
            //通过
            hmQuestionsAudits.setOperation("通过");
        }else {
            hmQuestionsAudits.setOperation("拒绝");
        }
        hmQuestionsAudits.setChktime(new Date());
        List<Users> usersList = usersService.findById(s);
        for (Users users : usersList) {
            hmQuestionsAudits.setCheckerid(users.getId());
        }
        //添加审核意见
        hmQuestionsAuditsMapper.insert(hmQuestionsAudits);
        return new ResponseResult(true);
    }

    /**
     * 测试查询全部
     * @return
     */
    @Override
    public List<HmQuestions> findAll() {
        return  hmQuestionsMapper.selectList(null);
    }

    //基础题库列表 if 判断
    private void ifpanduan(Query query, Integer[] ids, LambdaQueryWrapper<HmQuestions> wrapper) {
        //判断是否带有状态查询,如果有,则是精选题库的列表查询
        // TODO: 2022/1/12  复用代码,精选题库列表查询
        if (query.getChkState()!=null){
            wrapper.eq(HmQuestions::getChkState,query.getChkState());//todo 判断审核状态
            wrapper.eq(HmQuestions::getIschoice,1);//todo 筛选精选题
        } else if (query.getIsChoiceness()!=null){
            wrapper.eq(HmQuestions::getIschoice,1);//todo 查询全部精选题
        }else {
            wrapper.eq(HmQuestions::getIschoice,0);//todo 基础题库
        }
        if (query.getSubjectID() != null) {
            wrapper.eq(HmQuestions::getSubjectID, query.getSubjectID());//todo 学科
        }
        if (query.getDifficulty() != null) {
            wrapper.eq(HmQuestions::getDifficulty, query.getDifficulty());//todo 难度
        }
        if (query.getQuestionType() != null) {
            wrapper.eq(HmQuestions::getQuestionType, query.getQuestionType());//todo 试题类型
        }
        if (query.getTags() != null) {
            wrapper.eq(HmQuestions::getTags, query.getTags());//todo 标签名称
        }
        if (query.getProvince() != null) {
            wrapper.eq(HmQuestions::getProvince, query.getProvince());//todo 企业所在地
        }
        if (query.getCity() != null) {
            wrapper.eq(HmQuestions::getCity, query.getCity());//todo 企业所在城市
        }
        if (query.getKeyword() != null) {
            wrapper.like(HmQuestions::getQuestion, query.getKeyword());//todo 关键字(根据题干搜索)
        }
        if (query.getRemarks() != null) {
            wrapper.like(HmQuestions::getRemarks, query.getRemarks());//todo 题目备注
        }
        if (query.getDirection() != null) {
            wrapper.eq(HmQuestions::getDirection, query.getDirection());//todo 方向
        }
        if (query.getCreatorID() != null) {
            wrapper.eq(HmQuestions::getCatalogID, query.getCreatorID());//todo 录入人
        }
        if (query.getCatalogID() != null) {
            wrapper.eq(HmQuestions::getCatalogID, query.getCatalogID());//todo 目录
        }
        if (ids.length>0){
            wrapper.in(HmQuestions::getEnterpriseID,ids); //todo 通过参数企业简称获得企业id,进行判断
        }
    }
}
